import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login, getUserInfo } from '@/services/user'

export const useUserStore = defineStore('user', () => {
    const token = ref(localStorage.getItem('token') || '')
    const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || 'null'))

    // 用户登录
    const userLogin = async (loginData) => {
        try {
            const res = await login(loginData)
            token.value = res.token
            userInfo.value = res.userInfo

            // 保存到localStorage
            localStorage.setItem('token', res.token)
            localStorage.setItem('userInfo', JSON.stringify(res.userInfo))

            return res
        } catch (error) {
            throw error
        }
    }

    // 获取用户信息
    const fetchUserInfo = async () => {
        if (!token.value) return

        try {
            const res = await getUserInfo()
            userInfo.value = res
            localStorage.setItem('userInfo', JSON.stringify(res))
            return res
        } catch (error) {
            throw error
        }
    }

    // 用户登出
    const logout = () => {
        token.value = ''
        userInfo.value = null
        localStorage.removeItem('token')
        localStorage.removeItem('userInfo')
    }

    return {
        token,
        userInfo,
        userLogin,
        fetchUserInfo,
        logout,
    }
})